package pl.enigmatic.test;

import java.io.File;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import pl.enigmatic.util.Path;


public class DirectoryFilesList extends JList {

	public interface NameConverter {

		String convert(File file);
	}

	public interface ExtentionAcceptor {

		boolean accept(String ext);
	}

	private class FileWrapper {

		private final File file;

		public FileWrapper(final File file) {
			this.file = file;
		}

		@Override
		public String toString() {
			return nameConverter.convert(file);
		}
	}

	public static class NameConverterExtentionAcceptor implements NameConverter, ExtentionAcceptor {

		@Override
		public boolean accept(final String ext) {
			return true;
		}

		@Override
		public String convert(final File file) {
			if (file != null) { return Path.getFilenameNoExt(file.getAbsolutePath()); }
			return null;
		}
	}

	/** */
	private static final long serialVersionUID = 1L;

	private final DefaultListModel model;
	private final NameConverter nameConverter;

	public <X extends NameConverter & ExtentionAcceptor> DirectoryFilesList(final File dir, final X converter) {
		super(new DefaultListModel());
		nameConverter = converter;
		model = (DefaultListModel) getModel();
		for (final File f : dir.listFiles()) {
			if (f.isFile() && converter.accept(Path.getFileExt(f.getAbsolutePath()))) {
				model.addElement(new FileWrapper(f));
			}
		}
		addListSelectionListener(new ListSelectionListener() {

			int index = -1;

			@Override
			public void valueChanged(final ListSelectionEvent e) {
				final int i = getSelectedIndex();
				if (i != index) {
					final FileWrapper before = index > 0 && index < model.getSize() ? (FileWrapper) model.get(i) : null;
					final FileWrapper now = (FileWrapper) model.get(index = i);
					onFileSelected(before == null ? null : before.file, now == null ? null : now.file);
				}
			}
		});
	}

	public DirectoryFilesList(final File dir) {
		this(dir, new NameConverterExtentionAcceptor());
	}

	protected void onFileSelected(final File old, final File selected) {}

}
